package controller;

import conventer.ResultInfo;
import dao.UserDAO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import utilities.MailUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

@Controller
@RequestMapping("/regist")
public class RegistController {
    private static HashMap<String,String> validateCodes = new HashMap<>();

    @RequestMapping(value = "/validate", method = RequestMethod.POST)
    @ResponseBody
    public Object validateSender(@RequestParam(value = "email", required = true) String email){
        ResultInfo result = new ResultInfo();
        if(UserDAO.seekReuseEmail(email)){
            result.setResult("WRONG");
            result.setReason("THIS EMAIL IS USED");
            return result;
        }
        String vcode = String.valueOf(new Random().nextInt(9000)+1000);
        validateCodes.put(email,vcode);
        result.setResult(MailUtil.send(email,vcode)?"SUCCESS":"FAILED");
        return result;
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Object register(@RequestParam(value = "username", required = true) String username,
                           @RequestParam(value = "password", required = true) String password,
                           @RequestParam(value = "email", required = true) String email,
                           @RequestParam(value = "vcode", required = true) String vcode){
        ResultInfo result = new ResultInfo();

        if(validateCodes.get(email)!=null && validateCodes.get(email).equals(vcode));
        else{
            result.setResult("FAILED");
            result.setReason("VALIDATE CODE WRONG");
            return result;
        }
        if(!UserDAO.createUser(username,password,email)){
            result.setResult("FAILED");
            result.setReason("CREATE USER FAILED");
        }else{
            result.setResult("SUCCESS");
        }

        return result;
    }

}
